package com.cheerscpl.network;

import com.cheerscpl.DataHelper;
import com.cheerscpl.protocol.Channels;
import com.cheerscpl.protocol.model.DataPacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;

/**
 * Created by chenpuliang on 2017/6/4.
 */
public class ResolveHandler extends SimpleChannelInboundHandler<DataPacket> {

    private static final Logger logger = LoggerFactory.getLogger(ResolveHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String devName = InetAddress.getLocalHost().getHostName();
        logger.info("Device " + devName + " connected");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("设备号: " + InetAddress.getLocalHost().getHostName() + "掉线了");
        Channels.remove((SocketChannel) ctx.channel());
        logger.info("The current connect size is: " + Channels.getMapKeys().size());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            SocketChannel channel = (SocketChannel) ctx.channel();
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state() == IdleState.ALL_IDLE){ //超时关闭通道
                Channels.remove(channel);
                ctx.close();
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channels.remove((SocketChannel) ctx.channel());
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataPacket msg) throws Exception {
        //每次数据进来就写一次
        String devId = msg.getDevId();
        if(StringUtils.isNotBlank(devId)){
            Channels.remove(devId);
            Channels.add(devId, (SocketChannel) ctx.channel());
        }
        logger.debug("Business data parsing is begin......");
        DataHelper.receive(msg);
    }
}
